﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PropertyManagment.entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace PropertyManagment.config {
    public class AppDbContext : DbContext {

        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {

        }
        //手动创建DbSet
        //public DbSet<SysUser> sys_user { get; set; }
        //public DbSet<SysUserRole> sys_user_role { get; set; }
        //public DbSet<SysRole> sys_role { get; set; }
        //public DbSet<SysRoleMenu> sys_role_Menu { get; set; }
        //public DbSet<SysMenu> sys_Menu { get; set; }

        //动态创建DbSet
        protected override void OnModelCreating(ModelBuilder modelBuilder) {
            var assembly = Assembly.GetExecutingAssembly();
            foreach (Type type in assembly.ExportedTypes) {
                if (type.IsClass && type != typeof(BaseEntity) && typeof(BaseEntity).IsAssignableFrom(type)) {
                    //获取"Entity"方法
                    var method = modelBuilder.GetType().GetMethods().Where(x => x.Name == "Entity").FirstOrDefault();

                    if (method != null) {
                        method = method.MakeGenericMethod(new Type[] { type });
                        method.Invoke(modelBuilder, null);
                    }
                }
            }
            base.OnModelCreating(modelBuilder);
        }
    }

}
